package course.controller;

import cn.hutool.crypto.digest.DigestUtil;
import course.pojo.entity.Teacher;
import course.service.TeacherService;
import course.service.impl.TeacherServiceImpl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author HLF
 * @date 2022/7/5 16:01
 */
@WebServlet("/teacher/teacherLoginController")
public class TeacherLoginController extends BaseController {
    private TeacherService teacherService = new TeacherServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        String tpassword = req.getParameter("tpassword");

        if (!StringUtils.isNumeric(tid) || StringUtils.isBlank(tpassword) || StringUtils.isBlank(tid)) {
            req.setAttribute("msg", "教师编号或密码不能为空或格式不正确！");
            req.getRequestDispatcher("/teacher_login.jsp").forward(req, resp);
        }
        Teacher teacher = teacherService.getById(Integer.valueOf(tid));

        if (teacher == null) {
            req.setAttribute("msg", "教师编号或密码错误！");
            req.getRequestDispatcher("/teacher_login.jsp").forward(req, resp);
        } else {
            String pass = teacher.getTpassword();
            boolean check = DigestUtil.bcryptCheck(tpassword, pass);
            if (!check) {
                req.setAttribute("msg", "教师编号或密码错误！");
                req.getRequestDispatcher("/teacher_login.jsp").forward(req, resp);
            } else {
                HttpSession session = req.getSession();
                session.setAttribute("tteacher", teacher);
                session.setAttribute("role", "teacher");
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            }
        }
    }

    /**
     * 教师退出登录
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("tteacher");
        req.getSession().removeAttribute("role");

        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }
}
